package com.riven.bilibilidemo.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.riven.bilibilidemo.R;
import com.riven.bilibilidemo.utils.ClipboardUtil;
import com.riven.bilibilidemo.utils.NetUtils;
import com.riven.bilibilidemo.utils.UIUtils;

/**
 * @author rivenlee
 * @date 2017/3/16 18:41
 */

public class RecommendWebActivity extends AppCompatActivity {

    private String title ,value;
    private Toolbar toolbar;
    private WebView webView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webrecommend);
        initViews();
    }

    protected void initViews() {
        Intent intent = getIntent();
        if (intent != null) {
            title = intent.getStringExtra("title");
            value = intent.getStringExtra("value");
        }
        toolbar = (Toolbar) findViewById(R.id.recommend_toolBar);
        toolbar.setTitle(TextUtils.isEmpty(title) ? "详情" : title);
        setSupportActionBar(toolbar);
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }

        webView = (WebView) findViewById(R.id.recommend_webView);
        setupWebView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_browser, menu);
        return true;
    }

    /**
     * menu菜单监听
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;

            case R.id.menu_share:
                share();
                break;

            case R.id.menu_open:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(value));
                startActivity(intent);
                break;

            case R.id.menu_copy:
                ClipboardUtil.setText(RecommendWebActivity.this, value);
                UIUtils.getToast("已复制");
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void share() {

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
        intent.putExtra(Intent.EXTRA_TEXT, "来自「哔哩哔哩」的分享:" + value);
        startActivity(Intent.createChooser(intent, title));
    }

    private void setupWebView() {


        final WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webView.getSettings().setBlockNetworkImage(true);
        webView.setWebViewClient(new WebViewClient());
        webView.requestFocus(View.FOCUS_DOWN);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(value);
                return true;
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                if(!NetUtils.isConnected()){
                    new AlertDialog.Builder(RecommendWebActivity.this).setTitle("网络出错，请设置").setPositiveButton("确认",null).create().show();
                }{
                    super.onLoadResource(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//                if(errorCode == -2) {
//                        handler.sendEmptyMessage(3);//通知发送！
//                }
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                AlertDialog.Builder b2 = new AlertDialog
                        .Builder(RecommendWebActivity.this)
                        .setTitle(R.string.app_name)
                        .setMessage(message)
                        .setPositiveButton("确定", (dialog, which) -> result.confirm());

                b2.setCancelable(false);
                b2.create();
                b2.show();
                return true;
            }
        });
        webView.loadUrl(value);
    }

    //后退按钮监听
    @Override
    public void onBackPressed() {
        if (webView.canGoBack() && webView.copyBackForwardList().getSize() > 0
                && !webView.getUrl().equals(webView.copyBackForwardList()
                .getItemAtIndex(0).getOriginalUrl())) {
            webView.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onPause() {
        webView.reload();
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        webView.destroy();
        super.onDestroy();
    }
}
